package com.newworld.dmsapp2.register;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.HouseManageListActivity;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.bean.Function;
import com.newworld.dmsapp2.bean.Register;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class InvitecodeRegistActivity extends BaseActivity implements
		OnClickListener {
	private Button btn_invite_next;
	private EditText inviteCodeEdtTxt;

	protected String invitecode;
	protected String response;
	protected String message = "登录失败";
	protected String flag, relationtype;
	private String sessionId;
	private String LOG = "InvitecodeRegistActivity";

	private String relationtypeid = "";

	private Context context = this;
	private Handler progressBarHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Config.HANDLER_MSG_SUCCESS) {
			} else if (msg.what == 1) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
				finish();
			}
		}
	};
	private View timeline_view_2;
	private ImageView timeline_3stage_image_3;
	private TextView timeline_text_3;
	private ProgressBar progressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register_invitecode);
		initData();
		initViews();
		initEvents();
	}

	private void initData(){
		User user = SingleSample.getInstance(this).getUser();
		if(null != user){
			if(null != user.getSessionId() && !user.getSessionId().equals("")){
				sessionId = user.getSessionId();
			}
		}
	}
	@Override
	protected void initViews() {
		setTitlebarLeft(this, Config.TITLE_HOUSE_ATTATCH,
				HouseProvingActivity.class);
		btn_invite_next = (Button) findViewById(R.id.invitecode_btn);
		inviteCodeEdtTxt = (EditText) findViewById(R.id.invitecode_edit);
		timeline_view_2 = (View) findViewById(R.id.timeline_view_2);
		timeline_3stage_image_3 = (ImageView) findViewById(R.id.timeline_3stage_image_3);
		timeline_text_3 = (TextView) findViewById(R.id.timeline_text_3);
		progressBar = (ProgressBar) findViewById(R.id.proBar_get_data);
		if (UserMessageActivity.INTENT_FLAG == 1) {
			timeline_view_2.setVisibility(View.GONE);
			timeline_3stage_image_3.setVisibility(View.GONE);
			timeline_text_3.setVisibility(View.GONE);
			btn_invite_next.setText("邀请码关联");
		}
	}

	@Override
	protected void initEvents() {
		btn_invite_next.setOnClickListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.invitecode_btn:
			if (UserMessageActivity.INTENT_FLAG == 0) {
				inviteCodeRegisterIn();
			} else if (UserMessageActivity.INTENT_FLAG == 1) {
				inviteCodeRelate();
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 
	 * 非户主邀请码关联
	 * 
	 * @param view
	 */
	private void inviteCodeRelate() {
		// TODO Auto-generated method stub
		invitecode = inviteCodeEdtTxt.getText().toString();

		if (invitecode.equals("") || invitecode == null) {
			showShortToast("邀请码不能为空");
		} else {

			new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPreExecute() {
					if (Tool.isNetworkAvailable(InvitecodeRegistActivity.this)) {
						progressBar.setVisibility(android.view.View.VISIBLE);
					} else {
						Toast.makeText(InvitecodeRegistActivity.this,
								"请检查网络连接！", Toast.LENGTH_SHORT).show();
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if (Tool.isNetworkAvailable(InvitecodeRegistActivity.this)) {
						try {

							Map<String, String> map = new HashMap<String, String>();
							map.put("functionCode", "houseRelateComplete");
							map.put("inviteCode", invitecode);
							
							String result = HttpUtil.postRequestSe(Config.RELATE_URL, map,sessionId);
							Log.e("户主关联result", result);

							message = new JSONObject(result)
									.getString("message");
							flag = new JSONObject(result).getString("flag");

						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(InvitecodeRegistActivity.this, message,
							Toast.LENGTH_SHORT).show();
					if (flag.equals("success")) {

						Intent intent = new Intent(
								InvitecodeRegistActivity.this,
								HouseManageListActivity.class);
						startActivity(intent);
						finish();
					}

				}
			}.execute(null, null, null);
		}
	}

	/**
	 * 
	 * 户主点击注册
	 * 
	 * @param view
	 */
	public void inviteCodeRegisterIn() {

		/*
		 * if (ownername.length() == 0 || ownerphone.length() == 0) {
		 * showShortToast("用户名或手机号码不能为空"); } else { // 联网登陆子线程 3.加注销按钮，轻量级 xml表
		 * set user_id=0 //HandlerThread threadInternet = new
		 * HandlerThread("internet_thread"); //threadInternet.start(); Handler
		 * handlerInternet = new Handler();// 替换默认循环，即用线程代替
		 * handlerInternet.post(runInternet1);
		 * 
		 * // ProgressBar //progressbar.setVisibility(View.VISIBLE); }
		 */
		invitecode = inviteCodeEdtTxt.getText().toString();
		if (invitecode.length() == 0) {
			showShortToast("邀请码不能为空");
		} else {
			// 联网登陆子线程 3.加注销按钮，轻量级 xml表 set user_id=0
			HandlerThread threadInternet = new HandlerThread("internet_thread");
			threadInternet.start();
			Handler handlerInternet = new Handler(threadInternet.getLooper());// 替换默认循环，即用线程代替
			handlerInternet.post(runInternet1);

			// ProgressBar
			// progressbar.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 联网登录
	 */

	Runnable runInternet1 = new Runnable() {
		@Override
		public void run() {
			if (MyPreference.getInstance(InvitecodeRegistActivity.this)
					.getUserId() != 0) {
				// 判断有无网络
				if (Tool.isNetworkAvailable(context)) {

					progressBarHandler.obtainMessage(1).sendToTarget();

				} else {

				}
			} else {
				Register register = new Register();
				List<Register> registerList = DataSupport
						.findAll(Register.class);

				// 判断有无网络
				if (Tool.isNetworkAvailable(context)) {

					Register u = post(invitecode);

					if (flag.equals("success")) {
						UserMessageActivity.INTENT_USER_FLAG = 2;
						System.out.println("invitecode---11" + invitecode);
						Intent intent = new Intent(
								InvitecodeRegistActivity.this,
								UserMessageActivity.class);
						intent.putExtra("invitecode", invitecode);
						intent.putExtra("relationtypeid", relationtypeid);
						startActivity(intent);
						finish();
					}
					if (null == u) {
						progressBarHandler
								.sendEmptyMessage(Config.HANDLER_MSG_SUCCESS);
						showShortToast(message);
					} else {
						if (flag.equals("success")) {
							if (registerList.size() == 0) {
								register = u;
								// register.setOwnername(ownername);
								// register.setOwnerphone(ownerphone);
								// user.setUsertype("1");
								// 家人
								// String relationtypeid =
								// "402881f24feabdb5014feae3786e0007";
								/*
								 * if (username.equals("ht")) { usertype = "1";
								 * } else if (username.equals("zsx")) { usertype
								 * = "2"; } else if (username.equals("ljq")) {
								 * usertype = "3"; }
								 */
								register.setRelationtypeid(relationtypeid);
								// user.setSessionId(sessionId);
								register.save();
								// 2015修改登录

								List<Function> functions = register.getFuns();
								for (Function function : functions) {
									function.setRegister(register);
									function.save();
								}
								register.setFuns(functions);
								register.update(register.getId());
								if (register.isSaved()) {
									MyPreference.getInstance(context)
											.setRegisterId(register.getId());
									MyPreference.getInstance(context)
											.setRefreshState(true);
									SingleSample.resetInstance1();
									progressBarHandler
											.sendEmptyMessage(Config.HANDLER_MSG_SUCCESS);
									showShortToast("存储成功");
									Log.d("Store", "存储成功");

								} else {
									progressBarHandler
											.sendEmptyMessage(Config.HANDLER_MSG_FAIL);
									showShortToast("存储失败");
									Log.d("Store", "存储失败");
								}
							} else {
								// TODO
								register.updateAll();
								register = registerList.get(0);
								// register.setSessionId(sessionId);
								register.update(register.getId());
								MyPreference.getInstance(context)
										.setRegisterId(register.getId());
								SingleSample.resetInstance1();
							}
							progressBarHandler.sendEmptyMessage(0x111);

							// 转到用户管理界面
							UserMessageActivity.INTENT_USER_FLAG = 2;

							Intent intent = new Intent(
									InvitecodeRegistActivity.this,
									UserMessageActivity.class);
							/*
							 * intent.putExtra("houseID", houseId);
							 * System.out.println("houseID" + houseId);
							 * intent.putExtra("ownername", ownername);
							 * intent.putExtra("ownerphone", ownerphone);
							 * //intent.putExtra("postscript",);
							 */
							intent.putExtra("relationtypeid", relationtypeid);
							intent.putExtra("invitecode", invitecode);
							System.out.println("invitecode---22>" + invitecode);
							startActivity(intent);
							finish();
						} else {
							Log.d("连接flag", "false");
						}
					}
				} else {
					// WindowUtils.showPopupWindow(context);
					// 无网络，用户已经在本地数据库里
					if (registerList.size() > 0) {
						register = registerList.get(0);
						register.setToDefault("isactive");
						register.updateAll();
						// register.setSessionId(sessionId);
						register.updateAll();
						MyPreference.getInstance(context).setRegisterId(
								register.getId());
						SingleSample.resetInstance1();
						Intent intent = new Intent();
						/*
						 * intent.putExtra("houseID", houseId);
						 * System.out.println("houseID" + houseId);
						 * intent.putExtra("ownername", ownername);
						 * intent.putExtra("ownerphone", ownerphone);
						 * //intent.putExtra("postscript",);
						 */
						intent.putExtra("relationtypeid", relationtypeid);
						intent.putExtra("invitecode", invitecode);
						System.out.println("invitecode-->33" + invitecode);
						intent.setClass(InvitecodeRegistActivity.this,
								UserMessageActivity.class);
						startActivity(intent);
						finish();
					} else {
						Tool.setNetwork(context);
						showShortToast("当前无网络");
					}
					progressBarHandler.sendEmptyMessage(0x111);
				}
			}
		}
	};

	// 定义发送请求的方法
	private Register post(String ownername) {
		// 使用Map封装请求参数
		Map<String, String> map = new HashMap<String, String>();
		// 一期
		/*
		 * map.put("username", username); map.put("password", password);
		 */
		// 二期
		// relationtype = relationhost;
		map.put("inviteCode", invitecode);
		// map.put("ownerPhone", ownerphone);
		// map.put("houseId",houseId);
		// map.put("relationTypeId", relationtypeid);
		// 定义发送请求的URL
		// 发送请求

		response = "";
		Register register = null;
		try {
			String setsessionid = "";
			User user = SingleSample.getInstance(InvitecodeRegistActivity.this).getUser();
			if(null != user){
				if(null != user.getSessionId() && !user.getSessionId().equals("")){
					setsessionid = user.getSessionId();
				}
			}
			response = HttpUtil.postRequestSe(Config.SERVER_URL
					+ "registerController.do?checkInviteCode", map,setsessionid);
			// Log.d("post", response);
			System.out.print("response---->" + response);

			message = new JSONObject(response).getString("message");
			flag = new JSONObject(response).getString("flag");
			if (flag.equals("success")) {
				sessionId = HttpUtil.getsessionId();

				Log.d("response", response);

			} else {
				// showShortToast("登录JSON解析出错");
			}
			// showShortToast(message);
			showLogDebug(LOG, response);
			showLogDebug(LOG, message);
		} catch (JsonSyntaxException e) {
			showShortToast("登录JSON解析出错");
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			showShortToast("联网登录出错");
		}

		return register;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
